package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.OrdersMapper;
import com.itheima.reggie.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.yaml.snakeyaml.events.Event;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {
    @Autowired
    UserService userService;
    @Autowired
    ShoppingCartService shoppingCartService;
    @Autowired
    AddressBookService addressBookService;

    @Autowired
    OrderDetailService orderDetailService;
    @Override
    public void submit(Orders orders) {
        //A. 获得当前用户id, 查询当前用户的购物车数据
        long id = IdWorker.getId();
        Long userId = BaseContext.get();
        LambdaQueryWrapper<ShoppingCart> qw = new LambdaQueryWrapper<>();
        qw.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> userShopList = shoppingCartService.list(qw);
        if(userShopList == null || userShopList.size() == 0){
            throw new CustomException("购物车为空，不能下单");
        }
        //B. 根据当前登录用户id, 查询用户数据
        User user = userService.getById(userId);
        //C. 根据地址ID, 查询地址数据
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        //D. 组装订单明细数据, 批量保存订单明细
        AtomicInteger amount = new AtomicInteger(0);//使用这个变量，可以保证线程安全，高并发也不会出错；

        List<OrderDetail> orderDetailList = userShopList.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(id);
            orderDetail.setDishId(item.getDishId());
            orderDetail.setImage(item.getImage());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setNumber(item.getNumber());
            orderDetail.setName(item.getName());
            orderDetail.setAmount(item.getAmount());
            amount.getAndAdd(item.getAmount().multiply( new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());

        //saveOrderDetail.setImage();
        //E. 组装订单数据, 批量保存订单数据

        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setUserId(user.getId());
        orders.setNumber(String.valueOf(id));
        orders.setId(id);
        orders.setAmount(new BigDecimal(amount.get()));
        orders.setStatus(2);//2代表待派送
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());//收货人
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));//拼接地址的字符串
        this.save(orders);

        orderDetailService.saveBatch(orderDetailList);
        //F. 删除当前用户的购物车列表数据
        shoppingCartService.remove(qw);
    }
}
